import React, { FC, useContext, useState } from 'react';
import { Form, Input } from 'antd';

import { DesignRedux } from '../../DesignRedux';
import CheckImgModal from '../../CheckImgModal';
import { loopTreeNode } from '../../utils';

const AttributeFC = () => {
  const [form] = Form.useForm();

  const [isModalVisible, setIsModalVisible] = useState(false);
  // 在使用useContext解构出color中想要传递的值，就是最终返回给我们的值
  const { globalState, dispatch } = useContext(DesignRedux);
  const { rightNode, schema } = globalState; // 右侧元素属性

  const onClickShowImgModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const onChangeImg = (param) => {
    // 关闭躺框
    handleCancel();
    let newSchema = [...schema];
    loopTreeNode(newSchema, rightNode.key, (item) => {
      item.comProperty.imgUrl = param.img; // 更改图片
    });
    dispatch({
      schema: newSchema,
    });
  };

  form.setFieldsValue({
    ...rightNode,
  });

  const { imgUrl } = rightNode.comProperty;

  // TODO 动态修改各种属性
  return (
    <Form
      form={form}
      layout="vertical"
      onFieldsChange={(_, allFields) => {
        console.log('====', _);
      }}
    >
      <Form.Item label="ID" name="id" tooltip="组件唯一 id">
        <Input placeholder="组件 id" />
      </Form.Item>
      <Form.Item label="标题" name="title" tooltip="组件名称">
        <Input placeholder="组件名称" />
      </Form.Item>

      <Form.Item label="背景图" name="bg" tooltip="背景图">
        <img
          src={imgUrl}
          style={{
            height: 40,
            borderRadius: 3,
            width: '100%',
            cursor: 'pointer',
          }}
          onClick={onClickShowImgModal}
        />
      </Form.Item>

      <CheckImgModal
        visible={isModalVisible}
        onChange={onChangeImg}
        onClose={handleCancel}
      />
    </Form>
  );
};

export default AttributeFC;
